import React, { useState, useEffect } from 'react';
import {Card, Row, Col, Statistic, List, Tag, Progress, Button} from 'antd';
import {
    ProjectOutlined,
    CheckCircleOutlined,
    ClockCircleOutlined,
    ExclamationCircleOutlined
} from '@ant-design/icons';
import { taskService } from '../services/taskService';
import { getCurrentUser } from '../utils/auth';
import { debugAuth } from '../utils/auth';

const Dashboard = () => {
    const [stats, setStats] = useState({
        total: 0,
        completed: 0,
        inProgress: 0,
        pending: 0
    });
    const [recentTasks, setRecentTasks] = useState([]);
    const [loading, setLoading] = useState(true);

    const currentUser = getCurrentUser();

    // const handleDebug = () => {
    //     debugAuth();
    // };

    useEffect(() => {
        fetchDashboardData();
    }, []);

    const fetchDashboardData = async () => {
        try {
            // 获取任务统计
            const statsResponse = await taskService.getTaskStats();
            setStats(statsResponse.data);

            // 获取最近的任务
            const tasksResponse = await taskService.getCurrentUserTasks({
                page: 0,
                size: 5
            });
            setRecentTasks(tasksResponse.data.content || []);
        } catch (error) {
            console.error('获取仪表板数据失败:', error);
        } finally {
            setLoading(false);
        }
    };

    const getStatusColor = (status) => {
        const colors = {
            TODO: 'default',
            IN_PROGRESS: 'processing',
            COMPLETED: 'success',
            CANCELLED: 'error'
        };
        return colors[status] || 'default';
    };

    const getStatusText = (status) => {
        const texts = {
            TODO: '待开始',
            IN_PROGRESS: '进行中',
            COMPLETED: '已完成',
            CANCELLED: '已取消'
        };
        return texts[status] || status;
    };

    const completionRate = stats.total > 0 ? (stats.completed / stats.total * 100).toFixed(1) : 0;

    return (
        <div>
            <h1>欢迎回来，{currentUser?.username}！</h1>
            <Row gutter={[16, 16]} style={{ marginBottom: 24 }}>
                <Col xs={24} sm={12} md={6}>
                    <Card>
                        <Statistic
                            title="总任务数"
                            value={stats.total}
                            prefix={<ProjectOutlined />}
                            valueStyle={{ color: '#1890ff' }}
                        />
                    </Card>
                </Col>
                <Col xs={24} sm={12} md={6}>
                    <Card>
                        <Statistic
                            title="已完成"
                            value={stats.completed}
                            prefix={<CheckCircleOutlined />}
                            valueStyle={{ color: '#52c41a' }}
                        />
                    </Card>
                </Col>
                <Col xs={24} sm={12} md={6}>
                    <Card>
                        <Statistic
                            title="进行中"
                            value={stats.inProgress}
                            prefix={<ClockCircleOutlined />}
                            valueStyle={{ color: '#faad14' }}
                        />
                    </Card>
                </Col>
                <Col xs={24} sm={12} md={6}>
                    <Card>
                        <Statistic
                            title="待开始"
                            value={stats.pending}
                            prefix={<ExclamationCircleOutlined />}
                            valueStyle={{ color: '#f5222d' }}
                        />
                    </Card>
                </Col>
            </Row>

            <Row gutter={[16, 16]}>
                <Col xs={24} lg={12}>
                    <Card title="完成进度" loading={loading}>
                        <Progress
                            type="circle"
                            percent={completionRate}
                            format={() => `${completionRate}%`}
                            size={120}
                        />
                        <p style={{ textAlign: 'center', marginTop: 16 }}>
                            任务完成率
                        </p>
                    </Card>
                </Col>

                <Col xs={24} lg={12}>
                    <Card title="最近任务" loading={loading}>
                        <List
                            dataSource={recentTasks}
                            renderItem={task => (
                                <List.Item>
                                    <List.Item.Meta
                                        title={task.title}
                                        description={
                                            <div>
                                                <Tag color={getStatusColor(task.status)}>
                                                    {getStatusText(task.status)}
                                                </Tag>
                                                <span style={{ marginLeft: 8, color: '#666' }}>
                          {new Date(task.createdAt).toLocaleDateString()}
                        </span>
                                            </div>
                                        }
                                    />
                                </List.Item>
                            )}
                        />
                    </Card>
                </Col>
            </Row>
        </div>
    );

};

export default Dashboard;
